package com.bryant.bryant_weather.ui.home

import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.Rect
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TableLayout
import android.widget.TableRow
import android.widget.TextView
import android.widget.Toast
import androidx.core.graphics.toColorInt
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bryant.bryant_weather.R
import com.bryant.bryant_weather.WeatherGlobal
import com.bryant.bryant_weather.base.BaseBindingFragment
import com.bryant.bryant_weather.bean.ChangeCityBean
import com.bryant.bryant_weather.databinding.FragmentHomeBinding
import com.bryant.bryant_weather.event.ChangeCityClickEvent
import com.bryant.bryant_weather.utils.WeatherUtils
import com.qweather.sdk.response.air.v1.AirV1CurrentResponse
import com.qweather.sdk.response.air.v1.AirV1HourlyResponse
import com.qweather.sdk.response.weather.WeatherHourlyResponse
import com.qweather.sdk.response.weather.WeatherNowResponse
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


class HomeFragment : BaseBindingFragment<FragmentHomeBinding>(), HomeView {

    // ================================= 变量定义
    // 初始化Presenter
    private var mPresenter: HomePresenter? = null

    // 创建与主线程关联的Handler实例，用于执行定时任务
    private val handler = Handler(Looper.getMainLooper())

    // 创建ChangeCityDialog实例
    private var dialog: ChangeCityDialog? = null

    // 定义Runnable对象，用于周期性更新当前时间
    private val updateTimeRunnable = object : Runnable {
        override fun run() {
            updateCurrentTime()  // 调用方法更新界面显示的时间
            handler.postDelayed(this, 1000) // 每隔1000毫秒（即1秒）再次执行此任务
        }
    }
    // ------------------------------------------------------------------------------------------

    override fun onStart() {
        super.onStart()
        EventBus.getDefault().register(this)
    }

    override fun onStop() {
        super.onStop()
        EventBus.getDefault().unregister(this)
        stopTimeUpdates()
    }

    // ================================= onCreate生命周期
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }



    // ------------------------------------------------------------------------------------------
    // ================================= onResume生命周期
    override fun onResume() {
        super.onResume()
        if (binding.topBar.tvCityName.text.isEmpty()) {
            refreshLocationWeatherData(
                WeatherGlobal.getCityName(),
                WeatherGlobal.getLatitude(),
                WeatherGlobal.getLongitude(),

            )
        }
    }
    // ------------------------------------------------------------------------------------------


    // ================================= 绑定视图
    override fun initBinding(inflater: LayoutInflater, parent: ViewGroup?): FragmentHomeBinding {
        return FragmentHomeBinding.inflate(inflater, parent, false)
    }

    // ------------------------------------------------------------------------------------------


    // ================================= 初始化View生命周期
    override fun initView() {
        mPresenter = HomePresenter(this, HomeInteractor())

        // 1. 设置点击事件
        setClickListener()

        // 2. 设置未来24小时天气卡片布局和适配器
        binding.hourlyForecast.rvHourlyForecast.apply {
            // 1. 设置布局 -> 设置RecyclerView的布局管理器 - 为水平列表
            layoutManager = LinearLayoutManager(
                context,
                LinearLayoutManager.HORIZONTAL,
                false

            )

            // 2. 为RecyclerView设置适配器
            adapter = HourTempAdapter()

            // 3. 设置间距
            // 检查当前RecyclerView是否还没有添加任何ItemDecoration
            if (binding.hourlyForecast.rvHourlyForecast.itemDecorationCount == 0) {
                // 添加一个自定义的ItemDecoration来设置每个列表项的边距
                binding.hourlyForecast.rvHourlyForecast.addItemDecoration(
                    object : RecyclerView.ItemDecoration() {
                        override fun getItemOffsets(
                            outRect: Rect,              // 用于输出每个item的偏移量
                            view: View,                 // 当前item的视图
                            parent: RecyclerView,       // 父容器RecyclerView
                            state: RecyclerView.State   // RecyclerView的当前状态
                        ) {
                            super.getItemOffsets(outRect, view, parent, state)

                            // 获取当前item在适配器中的位置
                            val position = parent.getChildAdapterPosition(view)

                            if (position == 0) {
                                // 如果是第一个item，则左边没有间隔
                                outRect.left = 0
                            } else {
                                // 对于其他item，在左侧添加8dp的间距，并将其转换为像素
                                context?.let {
                                    outRect.left = WeatherUtils.dip2px(it, 10f)
                                }
                            }
                        }
                    })
            }
        }

        // 3. 设置未来24小时空气卡片布局和适配器
        binding.hourlyAirQuality.rvHourlyAirQuality.apply {
            // 1. 设置布局
            layoutManager  =LinearLayoutManager(
                context,
                LinearLayoutManager.HORIZONTAL,
                false
            )
            // 2. 设置适配器
            adapter = HourAirQualityAdapter()

            // 3. 设置间距
            if (binding.hourlyAirQuality.rvHourlyAirQuality.itemDecorationCount == 0){
                binding.hourlyAirQuality.rvHourlyAirQuality.addItemDecoration(
                    object : RecyclerView.ItemDecoration() {
                        override fun getItemOffsets(
                            outRect: Rect,              // 用于输出每个item的偏移量
                            view: View,                 // 当前item的视图
                            parent: RecyclerView,       // 父容器RecyclerView
                            state: RecyclerView.State   // RecyclerView的当前状态
                        ) {
                            super.getItemOffsets(outRect, view, parent, state)
                            // 获取当前item在适配器中的位置
                            val position = parent.getChildAdapterPosition(view)

                            if (position == 0) {
                                // 如果是第一个item，则左边没有间隔
                                outRect.left = 0
                            } else {
                                // 对于其他item，在左侧添加8dp的间距，并将其转换为像素
                                context?.let {
                                    outRect.left = WeatherUtils.dip2px(it, 10f)
                                }
                            }
                        }
                    }
                )
            }
        }

    }
    // ------------------------------------------------------------------------------------------


    // ======================================= 继承自HomeView =====================================

    // ================================= 获取实时天气数据成功回调
    @SuppressLint("SetTextI18n")
    override fun getMainWeatherDataSuccess(response: WeatherNowResponse) {
        hideLoading()
        // 填充当前天气卡片数据
        stopTimeUpdates()
        updateCurrentTime()
        startTimeUpdates()

        binding.topBar.tvCityName.text = WeatherGlobal.getCityName()
        // 显示当前天气卡片
        binding.currentWeatherCard.llCurrentWeatherContainer.visibility = View.VISIBLE
        binding.currentWeatherCard.tvRefreshTime.text =
            WeatherUtils.formatTime(response.now.obsTime) + " 更新"
        binding.currentWeatherCard.tvTemperature.text = response.now.temp
        binding.currentWeatherCard.tvDegreeSymbol.visibility = View.VISIBLE

        // 根据天气状况的图标代码, 绘制对应的图标
        context?.let {
            var iconCode = "_" + response.now.icon?.replace("-", "_")
            if (WeatherUtils.isDrawableInRClass(it, iconCode)) {
                val drawable = WeatherUtils.getDrawableByName(it, iconCode)
                drawable?.let {
                    binding.currentWeatherCard.ivWeatherIcon.setImageDrawable(drawable)
                }
                binding.currentWeatherCard.ivWeatherIcon.visibility = View.VISIBLE
            } else {
                binding.currentWeatherCard.ivWeatherIcon.visibility = View.GONE
            }
        }

        //数据拼接，如 晴 | 北风3级 | 当前体感20度
        var constructText = ""
        if (response.now.text.isNotEmpty()) {
            constructText += response.now.text
        }
        if (response.now.windDir.isNotEmpty() && response.now.windScale.isNotEmpty()) {
            constructText += " | " + response.now.windDir + response.now.windScale + "级"
        }
        if (response.now.feelsLike.isNotEmpty()) {
            constructText += " | 当前体感" + response.now.feelsLike + "°"
        }
        if (constructText.isNotEmpty()) {
            binding.currentWeatherCard.tvWeatherCondition.text = constructText
        } else {
            binding.currentWeatherCard.tvWeatherCondition.text = "暂无数据"
        }

        binding.currentWeatherCard.tvHumidity.text = response.now.humidity + "%"
        binding.currentWeatherCard.tvWindSpeed.text = response.now.windSpeed
        binding.currentWeatherCard.tvPressure.text = response.now.pressure
    }
    // ------------------------------------------------------------------------------------------

    // ================================= 获取实时天气数据失败回调
    override fun getMainWeatherDataFailed(msg: String) {
        hideLoading()
        binding.currentWeatherCard.llCurrentWeatherContainer.visibility = View.GONE
        Toast.makeText(mActivity, msg, Toast.LENGTH_SHORT).show()
    }
    // ------------------------------------------------------------------------------------------

    // ================================= 获取24小时天气数据成功回调
    override fun get24HourWeatherDataSuccess(response: WeatherHourlyResponse) {
        // 1. 获取成功先将24小时预报卡片显示
        binding.hourlyForecast.root.visibility = View.VISIBLE

        // 2. 填充24小时预报数据
        response.hourly?.let { hourlist ->
            // 将请求获取到的数据提交给适配器
            (binding.hourlyForecast.rvHourlyForecast.adapter as HourTempAdapter).submitList(hourlist)
        }

    }
    // ------------------------------------------------------------------------------------------

    // ================================= 获取24小时天气数据失败回调 - 继承自HomeView
    override fun get24HourWeatherDataFailed(msg: String) {
        // 获取失败不显示24小时卡片
        binding.hourlyForecast.root.visibility = View.GONE
    }
    // ------------------------------------------------------------------------------------------

    // ================================= 获取空气质量数据成功回调
    override fun getAirQualityDataSuccess(response: AirV1CurrentResponse) {
        // 1. 获取成功先将空气质量卡片显示
        binding.airQualityCard.root.visibility = View.VISIBLE
        // 2. 填充数据
        // 填充空气质量卡片数据
        response.indexes?.let { indexList ->
            var airIndex = indexList[0]
            binding.airQualityCard.tvAirQualityIndex.text = airIndex.aqiDisplay

            // 设置进度条
            binding.airQualityCard.progressAirQuality.progress = airIndex.aqi.toInt()
            binding.airQualityCard.tvAirQualityLevel.text = airIndex.category

            // 设置背景色
            val gradientDrawable = GradientDrawable()
            gradientDrawable.shape = GradientDrawable.RECTANGLE
            gradientDrawable.cornerRadius = 16f // 圆角半径（像素）
            gradientDrawable.setColor(
                Color.rgb(
                    airIndex.color.red,
                    airIndex.color.green,
                    airIndex.color.blue
                )
            ) // 设置颜色
            binding.airQualityCard.tvAirQualityLevel.background = gradientDrawable

            // 填充健康建议
            if (airIndex.health.effect.isNotEmpty()) {
                binding.airQualityCard.tvAirQualityHealthEffect.visibility = View.VISIBLE
                binding.airQualityCard.tvAirQualityHealthEffect.text =
                    "健康影响： " + airIndex.health.effect
            } else {
                binding.airQualityCard.tvAirQualityHealthEffect.visibility = View.GONE
            }
        }

        //污染度及其浓度
        if (response.pollutants?.isNotEmpty() == true) {
            var pollutantMap = mutableMapOf<String, String>()
            pollutantMap["污染物"] = "浓度及单位"
            response.pollutants.let { pollutantList ->
                for (pollutant in pollutantList) {
                    if (pollutant.name.isNotEmpty()) {
                        var pollutantDescription = ""
                        pollutantDescription += pollutant.concentration.value.toString() + " " + pollutant.concentration.unit
                        pollutantMap[pollutant.name] = pollutantDescription
                    }
                }
            }
            if (response.pollutants.isNotEmpty()) {
                binding.airQualityCard.tlAirQuality.visibility = View.VISIBLE
                refreshAirQualityData(pollutantMap)
            } else {
                binding.airQualityCard.tlAirQuality.visibility = View.GONE
            }
        } else {
            binding.airQualityCard.tlAirQuality.visibility = View.GONE
        }

        //监测站数据
        var stationDescription = ""
        response.stations.let { stationList ->
            for (station in stationList) {
                if (station.name.isNotEmpty()) {
                    if (stationDescription.isNotEmpty()) {
                        stationDescription += " | "
                    }
                    stationDescription += station.name
                }
            }
        }
        if (stationDescription.isNotEmpty()) {
            binding.airQualityCard.tvAirQualityStations.visibility = View.VISIBLE
            binding.airQualityCard.tvAirQualityStations.text = "监测站： " + stationDescription
        } else {
            binding.airQualityCard.tvAirQualityStations.visibility = View.GONE
        }
    }

    fun refreshAirQualityData(dataMap: Map<String, String>) {
        // 清空现有行
        binding.airQualityCard.tlAirQuality.removeAllViews()
        dataMap.forEach { (key, value) ->
            addTableRow(key, value)
        }
    }

    fun addTableRow(name: String, age: String) {
        val row = TableRow(mActivity).apply {
            layoutParams = TableLayout.LayoutParams(
                TableLayout.LayoutParams.MATCH_PARENT,
                TableLayout.LayoutParams.WRAP_CONTENT
            )
            top = WeatherUtils.dip2px(context, 16f) // 设置行间距
            gravity = Gravity.CENTER  // 行内容居中
        }

        // No.1列
        val tvName = TextView(mActivity).apply {
            text = name
            gravity = Gravity.CENTER  // 单元格内容居中
            setTextColor("#ffffff".toColorInt())
            setPadding(
                WeatherUtils.dip2px(context, 16f),
                WeatherUtils.dip2px(context, 12f),
                WeatherUtils.dip2px(context, 16f),
                WeatherUtils.dip2px(context, 12f)
            )
            layoutParams = TableRow.LayoutParams(
                0,
                TableRow.LayoutParams.WRAP_CONTENT,
                1f  // 关键：权重设为1
            )
        }

        // No.2列
        val tvAge = TextView(mActivity).apply {
            text = age
            gravity = Gravity.CENTER
            setTextColor("#ffffff".toColorInt())
            setPadding(
                WeatherUtils.dip2px(context, 16f),
                WeatherUtils.dip2px(context, 12f),
                WeatherUtils.dip2px(context, 16f),
                WeatherUtils.dip2px(context, 12f)
            )
            layoutParams = TableRow.LayoutParams(
                0,
                TableRow.LayoutParams.WRAP_CONTENT,
                1f
            )
        }

        row.addView(tvName)
        row.addView(tvAge)
        binding.airQualityCard.tlAirQuality.addView(row)
    }
    // ------------------------------------------------------------------------------------------

    // ================================= 获取空气质量数据失败回调
    override fun getAirQualityDataFailed(msg: String) {
        binding.airQualityCard.root.visibility = View.GONE
    }

    // ================================= 获取24小时空气质量数据成功回调
    override fun get24HourAirQualityDataSuccess(response: AirV1HourlyResponse) {
        // 1. 显示卡片
        binding.hourlyAirQuality.root.visibility = View.VISIBLE

        // 2. 填充数据
        response.hours?.let { hourList ->
            (binding.hourlyAirQuality.rvHourlyAirQuality.adapter as HourAirQualityAdapter).submitList(
                hourList
            )
        }
    }

    // ================================= 获取24小时空气质量数据失败回调
    override fun get24HourAirQualityDataFailed(msg: String) {
        binding.hourlyAirQuality.root.visibility = View.GONE

    }

    override fun refreshCityList(cityList: MutableList<ChangeCityBean>) {
       // 给城市弹层传递cityList
        dialog?.refreshCityList(cityList)
    }
    // ------------------------------------------------------------------------------------------


    // ====================================== 自定义函数 ===============================================

    //  =========================== 显示切换城市的dialog====================================

    fun showChangeDialog(){
        mActivity?.let {
            dialog = ChangeCityDialog(it, R.style.BottomSheetDialog_Immersion)
            dialog?.setOnDismissListener {
                if(dialog != null){
                    dialog = null
                }
            }
            dialog?.show()
        }
    }
    /**
     * 订阅ChangeCityClickEvent事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun changeCitySuccess(event: ChangeCityClickEvent){
        /**
         * 切换城市成功，刷新数据
         */
        event.changeCityBean.let {
            refreshLocationWeatherData(it.cityName, it.longitude.toString(),it.latitude.toString())
        }

    }
    // ------------------------------------------------------------------------------------------
    // ================================= 开始更新时间函数
    private fun startTimeUpdates() {
        handler.post(updateTimeRunnable)
    }
    // ------------------------------------------------------------------------------------------

    // ================================ 停止更新时间函数
    private fun stopTimeUpdates() {
        handler.removeCallbacks(updateTimeRunnable)
    }
    // ------------------------------------------------------------------------------------------

    // ================================= 更新当前时间函数
    @SuppressLint("SetTextI18n")
    private fun updateCurrentTime() {
        var currTime = System.currentTimeMillis()
        binding.currentWeatherCard.tvWeekday.text = WeatherUtils.formatUTC(currTime, "EEEE")
        binding.topBar.tvCurrentTime.text = WeatherUtils.formatUTC(currTime, "yyyy-MM-dd HH:mm:ss")
    }
    // ------------------------------------------------------------------------------------------

    // ================================= 通过mPresenter -> 刷新当前位置天气数据
    fun refreshLocationWeatherData(
        cityName: String,
        latitude: String,
        longitude: String,
    ) {
        binding.topBar.tvCityName.text = cityName
        mPresenter?.setCityLocationParams(cityName, longitude, latitude)
        showLoading()
        mPresenter?.requestMainWeatherData()

    }

    // ------------------------------------------------------------------------------------------

    // ================================= 点击事件函数
    private fun setClickListener() {
        // 1. 点击 点我刷新
        binding.currentWeatherCard.btnRealTime.setOnClickListener {
            showLoading()
            mPresenter?.requestMainWeatherData()
        }
        // 2. 顶部栏点击事件
        binding.topBar.llChangeCityContainer.setOnClickListener {
            mPresenter?.requestCityListData()
            showChangeDialog()
        }
    }

}